package nl.hva.web.mvcwebapp.controllers;

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import nl.hva.web.mvcwebapp.classes.UserClass;
import nl.hva.web.mvcwebapp.doa.UserDAO;
import nl.hva.web.mvcwebapp.models.User;
import nl.hva.web.mvcwebapp.service.HibernateUtil;
import org.hibernate.Session;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.hibernate.*;
import sun.misc.BASE64Encoder;

public class UserController extends HttpServlet {

    private String address = "";
    String redirect = "false";
    public static User userData;
    public static int userAccountType;
    public static String[] validationError;
    public static String userAccountFirstName;
    public static int userAccountId;
    public static String userAccountUsername;
    public String userAccountPassword;
    public String userAccountPassword2;
    public String userAccountEmail;
    public String userAccountLastName;
    private static User userFail;
    private static int id2;
    public static HttpSession session_user;
    public static User viewProfile;

    public ArrayList getPaths() {
        ArrayList paths = new ArrayList();
        paths.add(0, "/users");
        paths.add(1, "/user/edit");
        paths.add(2, "/user/user_profile");
        paths.add(3, "/user/new");
        paths.add(4, "/user/delete");
        paths.add(5, "/register");
        paths.add(6, "/login");
        paths.add(7, "/logout");
        paths.add(8, "/user/user_changepw");
        return paths;
    }

    public ArrayList getPathsJSP() {
        ArrayList paths_jsp = new ArrayList();
        paths_jsp.add(0, "/user/users.jsp");
        paths_jsp.add(1, "/user/user_edit.jsp");
        paths_jsp.add(2, "/user/user_profile.jsp");
        paths_jsp.add(3, "/user/user_edit.jsp");
        paths_jsp.add(4, "/user/users.jsp");
        paths_jsp.add(5, "/user/register.jsp");
        paths_jsp.add(6, "/user/login.jsp");
        paths_jsp.add(7, "/index.jsp");
        paths_jsp.add(8, "/user/user_changepw.jsp");
        return paths_jsp;
    }
    /*
     * HTTP GET request
     */

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {

        ArrayList paths = getPaths();
        ArrayList paths_jsp = getPathsJSP();

        String path = request.getServletPath();
        session_user = request.getSession();
//        if(Integer.parseInt(session_user.getAttribute("user_id").toString()) < 1){
//        session_user.setAttribute("user_id", 0);
//        }

        for (int i = 0; i < paths.size(); i++) {
            try {
                if (path.equals(paths.get(i).toString())
                        || path.substring(0, path.toString().length() - 1).equals(paths.get(i).toString())) {
                    address = paths_jsp.get(i).toString();
                    // ---------------- /users --------------------
                    if (i == 0) {
                        List<User> userlist = UserDAO.getAllUSers();
                        request.setAttribute("pageTitle", "Users");
                        request.setAttribute("gebruikersUitSessie", userlist);
                        request.setAttribute("aantalGebruikers", userlist.size());
                    } // ---------------- /user/edit --------------------
                    else if (i == 1) {
                        int id = Integer.parseInt(request.getParameter("id"));
                        User user = UserDAO.getUser(id);
                        request.setAttribute("user", user);
                        request.setAttribute("buttonTitle", "Edit");
                        request.setAttribute("pageTitle", "Edit user");
                    } // ---------------- /user/profile --------------------
                    else if (i == 2) {
                        viewProfile = UserDAO.getUser(Integer.parseInt(request.getParameter("id")));
//                        User viewProfile = UserDAO.getUser(Integer.parseInt(request.getParameter("id")));
//                        int id = (Integer) session_user.getAttribute("user_id");
//                        UserDAO.getUserCourses(id); // Dit zou moeten werken maar enroll klopt geen zak van geloof ik.
                        request.setAttribute("user", viewProfile);
                        request.setAttribute("usertype", UserClass.getUsertypeString(viewProfile.getUserType()));
                        request.setAttribute("pageTitle", viewProfile.getUserFirstName() + " " + viewProfile.getUserLastName() + "'s Profile");
                    } // ---------------- /user/new --------------------
                    else if (i == 3) {
                        request.setAttribute("pageTitle", "New user");
                        request.setAttribute("buttonTitle", "Add");
                    } // ---------------- /user/delete --------------------
                    else if (i == 4) {
                        int id = Integer.parseInt(request.getParameter("id"));
                        UserDAO.deleteUser(id);
                        response.sendRedirect(response.encodeRedirectURL("../users"));
                        return;
                    } // ---------------- /user/register --------------------
                    else if (i == 5) {
                        request.setAttribute("pageTitle", "Register");
                    } // ---------------- /user/login --------------------
                    else if (i == 6) {
                        request.setAttribute("pageTitle", "Login");
                    } // ---------------- /user/logout --------------------
                    else if (i == 7) {
                        session_user.setAttribute("user_id", 0);
                        session_user.removeAttribute("user_firstname");
                        session_user.removeAttribute("user_lastname");
                        session_user.removeAttribute("user_type");
                        RequestDispatcher dispatcher = request.getRequestDispatcher("/index.jsp");
                        dispatcher.forward(request, response);
                    } // ---------------- /user/changepw --------------------
                    else if (i == 8) {
                        System.out.println("komtiewelhier?");
                        int id = Integer.parseInt(request.getParameter("id"));
                        User user = UserDAO.getUser(id);
                        request.setAttribute("user", user);
                        request.setAttribute("buttonTitle", "Confirm");
                        request.setAttribute("pageTitle", "Change password");
                    }
                }
            } catch (Exception E) {
            }
        }
        request.setAttribute("usertypes", UserClass.getUsertypes());
        if (redirect == "true") {
            response.sendRedirect(response.encodeRedirectURL("../users"));
        } else {
            RequestDispatcher dispatcher = request.getRequestDispatcher(address);
            dispatcher.forward(request, response);
        }

    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {

        ArrayList paths = getPaths();
        ArrayList paths_jsp = getPathsJSP();
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction tx = session.beginTransaction();
        String path = request.getServletPath();
        session_user = request.getSession();
        int user_type =0;
      

        for (int i = 0; i < paths.size(); i++) {
            try {
                if (path.equals(paths.get(i).toString())
                        || path.substring(0, path.toString().length() - 1).equals(paths.get(i).toString())) {
                    address = paths_jsp.get(i).toString();
                    // ---------------- /user/new + /user/edit --------------------
                    if (i == 1 || i == 3) {
                        if (request.getParameter("id") != null && !request.getParameter("id").isEmpty()) {
                            int id = Integer.parseInt(request.getParameter("id"));
                            User user = (User) session.get(User.class, id);
                            String pass_temp = user.getPassword();
                            User user_update = getUserFromRequest(request, user);
                            if (user_update.getPassword() == pass_temp || user_update.getPassword() == "") {
                                user_update.setPassword(pass_temp);
                            } else {
                                String password_new = user_update.getPassword();
                                MessageDigest msgDigest = null;
                                String hashValue = null;
                                try {
                                    msgDigest = MessageDigest.getInstance("SHA1");
                                    msgDigest.update(password_new.getBytes("UTF-8"));
                                    byte rawByte[] = msgDigest.digest();
                                    hashValue = (new BASE64Encoder()).encode(rawByte);

                                } catch (NoSuchAlgorithmException e) {
                                    System.out.println("No Such Algorithm Exists");
                                } catch (UnsupportedEncodingException e) {
                                    System.out.println("The Encoding Is Not Supported");
                                }
                                user_update.setPassword(hashValue);
                            }
                            session.update(user_update);
                            session_user.setAttribute("user_type", user_update.getUserType());
                        } else {
                            User formUser = getUserFromRequest(request, new User());
                            String clearPassword = request.getParameter("password");
                            MessageDigest msgDigest = null;
                            String hashValue = null;
                            try {
                                msgDigest = MessageDigest.getInstance("SHA1");
                                msgDigest.update(clearPassword.getBytes("UTF-8"));
                                byte rawByte[] = msgDigest.digest();
                                hashValue = (new BASE64Encoder()).encode(rawByte);

                            } catch (NoSuchAlgorithmException e) {
                                System.out.println("No Such Algorithm Exists");
                            } catch (UnsupportedEncodingException e) {
                                System.out.println("The Encoding Is Not Supported");
                            }
                            formUser.setPassword(hashValue);
                            session.save(formUser);
                        }
                        tx.commit();
                        //Redirect to right page after update
                        user_type = Integer.valueOf("" + session_user.getAttribute("user_type"));
                        if(user_type == 1 ||user_type ==2 ){
                            response.sendRedirect(response.encodeRedirectURL("../index"));
                        }else{
                            response.sendRedirect(response.encodeRedirectURL("../users"));
                        }
                        

                    }
                    if (i == 2) {
                    }
                    // ---------------- /register --------------------
                    if (i == 5) {
                        String adress;
                        User formUser = getUserFromRequest(request, new User());
                        userFail = formUser;
                        validationError = UserDAO.checkValidation(request);
                        if (validationError[0] == null && validationError[1] == null && validationError[2] == null && validationError[3] == null && validationError[4] == null && validationError[5] == null && validationError[6] == null && validationError[7] == null && validationError[8] == null && validationError[9] == null) {
                            String clearPassword = request.getParameter("password");
                            MessageDigest msgDigest = null;
                            String hashValue = null;
                            try {
                                msgDigest = MessageDigest.getInstance("SHA1");
                                msgDigest.update(clearPassword.getBytes("UTF-8"));
                                byte rawByte[] = msgDigest.digest();
                                hashValue = (new BASE64Encoder()).encode(rawByte);

                            } catch (NoSuchAlgorithmException e) {
                                System.out.println("No Such Algorithm Exists");
                            } catch (UnsupportedEncodingException e) {
                                System.out.println("The Encoding Is Not Supported");
                            }
                            formUser.setPassword(hashValue);
                            session.save(formUser);
                            tx.commit();
                            adress = "/user/login.jsp";
                        } else {
                            request.setAttribute("validationError", validationError);
                            request.setAttribute("FilledInInfo", userFail);
                            request.setAttribute("pageTitle", "Register");
                            adress = "/user/register.jsp";
                        }

                        RequestDispatcher dispatcher = request.getRequestDispatcher(adress);
                        dispatcher.forward(request, response);

                    }
                    // ---------------- /login --------------------
                    if (i == 6) {
                        userData = UserDAO.checkLogin(request); // USERDATA BEVAT ALLE GEGEVENS VAN DE INGELOGDE GEBRUIKER!!!
                        //System.out.println(userData);
                        if (userData != null) {
                            session_user.setAttribute("user_id", userData.getUserId());
                            session_user.setAttribute("user_firstname", userData.getUserFirstName());
                            session_user.setAttribute("user_lastname", userData.getUserLastName());
                            session_user.setAttribute("user_type", userData.getUserType());
                            session_user.setAttribute("user_username", userData.getUserName());
                            session_user.setAttribute("user_profilepicture", userData.getProfilepicture());

                            response.sendRedirect(response.encodeRedirectURL("index"));
                        } else {
                            ArrayList loginError = new ArrayList();
                            loginError.add("Username or password incorrect!");
                            request.setAttribute("loginError", loginError);
                            RequestDispatcher dispatcher = request.getRequestDispatcher("/user/login.jsp");
                            dispatcher.forward(request, response);
                        }
                    } // ---------------- /changepw --------------------
                    if (i == 8) {
                        String adress;
                        if (id2 == 0) {
                            id2 = Integer.parseInt(request.getParameter("id"));
                        }
                        User user = (User) session.get(User.class, id2);
                        String oldpw = request.getParameter("passwordOld");
                        String newpw = request.getParameter("passwordNew");
                        String repeatpw = request.getParameter("password-repeat");
                        request.setAttribute("oldpwError", "");
                        request.setAttribute("newpwError", "");

                        MessageDigest msgDigest = null;
                        String hashValue = null;
                        try {
                            msgDigest = MessageDigest.getInstance("SHA1");
                            msgDigest.update(user.getPassword().getBytes("UTF-8"));
                            byte rawByte[] = msgDigest.digest();
                            hashValue = (new BASE64Encoder()).encode(rawByte);

                        } catch (NoSuchAlgorithmException e) {
                            System.out.println("No Such Algorithm Exists");
                        } catch (UnsupportedEncodingException e) {
                            System.out.println("The Encoding Is Not Supported");
                        }

                        if (newpw.equals(repeatpw) && oldpw.equals(hashValue) && newpw.length() > 5) {
                            System.out.println("Password was succesfully changed!");
                            user.setPassword(newpw);
                            user.setPassword2(repeatpw);
                            request.setAttribute("user", user);
                            request.setAttribute("usertype", UserClass.getUsertypeString(user.getUserType()));
                            request.setAttribute("pageTitle", user.getUserFirstName() + " " + user.getUserLastName() + "'s Profile");
                            session.update(user);
                            tx.commit();
                            adress = "/user/user_profile.jsp";
                        } else {
                            if (!oldpw.equals(user.getPassword())) {
                                request.setAttribute("oldpwError", "You filled in your current password incorrectly.");
                            }
                            if (!newpw.equals(repeatpw)) {
                                request.setAttribute("newpwError", "The new passwords you filled in do not match.");
                            }
                            if (newpw.length() < 6) {
                                request.setAttribute("pwlengthError", "The new password is too short! This instabilizes the security of your account.");
                            }
                            request.setAttribute("pageTitle", "Change password");
                            request.setAttribute("buttonTitle", "Confirm");
                            adress = "/user/user_changepw.jsp";
                        }
                        RequestDispatcher dispatcher = request.getRequestDispatcher(adress);
                        dispatcher.forward(request, response);
                    }
                }

            } catch (Exception E) {
            }
        }
    }

    public User getUserFromRequest(HttpServletRequest request, User user) {

        if (request.getParameter("id") != null && !request.getParameter("id").isEmpty()) {
            user.setUserId(Integer.parseInt(request.getParameter("id")));
        }
        if (request.getParameter("username") != null) {
            user.setUserName(request.getParameter("username"));
        }
        if (request.getParameter("password") != null) {
            user.setPassword(request.getParameter("password"));
        }
        if (request.getParameter("password2") != null) {
            user.setPassword2(request.getParameter("password2"));
        }
        if (request.getParameter("firstname") != null) {
            user.setUserFirstName(request.getParameter("firstname"));
        }
        if (request.getParameter("lastname") != null) {
            user.setUserLastName(request.getParameter("lastname"));
        }
        if (request.getParameter("email") != null) {
            user.setUserEmail(request.getParameter("email"));
        }

        String[] templandoforigin = request.getParameterValues("landOfOrigin");
        int temploo = Integer.parseInt(templandoforigin[0]);
        if (temploo == 1) {
            user.setUserLandOfOrigin("Nederlands");
        }
        if (temploo == 2) {
            user.setUserLandOfOrigin("English");
        }
        if (temploo == 3) {
            user.setUserLandOfOrigin("Not specified, English");
        }

        String PROFILEPICTURE = "http://icons.iconarchive.com/icons/visualpharm/must-have/256/User-icon.png";
        if (request.getParameter("profilepicture") == null) {
            user.setProfilepicture(PROFILEPICTURE);
        } else if (request.getParameter("profilepicture") != null) {
            user.setProfilepicture(request.getParameter("profilepicture"));
        }
        String[] tempusertype = request.getParameterValues("usertype");
        int tempusertype2 = Integer.parseInt(tempusertype[0]);
        if (tempusertype2 == 1) {
            user.setUserType(1);
        }
        if (tempusertype2 == 2) {
            user.setUserType(2);
        }
        if (tempusertype2 == 3) {
            user.setUserType(3);
        }

        return user;
    }
}
